package com.lcf.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.utils.UserUtils;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.UserScoreDao;
import com.lcf.system.entity.UserScore;
import com.lcf.system.query.ScorePageQuery;
import com.lcf.system.service.UserScoreService;
import com.lcf.system.vo.UserScoreRankVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户积分(UserScore)表服务实现类
 *
 * @author lcf
 * @since 2025-04-24 21:14:32
 */
@Service("userScoreService")
public class UserScoreServiceImpl extends ServiceImpl<UserScoreDao, UserScore> implements UserScoreService {

    @Override
    public Integer myScore() {
        UserScore one = Db.lambdaQuery(UserScore.class).eq(UserScore::getOpenId, UserUtils.getOpenId()).one();
        return one == null ? 0 : one.getScore();
    }

    @Override
    public PageVO<UserScoreRankVO> rank(ScorePageQuery query) {
        Page<UserScore> page = Db.lambdaQuery(UserScore.class)
                .orderByDesc(UserScore::getScore)
                .page(query.toPage());
        if (page.getRecords().isEmpty()) {
            return new PageVO<>(page, UserScoreRankVO.class);
        }

        PageVO<UserScoreRankVO> pageVO = new PageVO<>(page, UserScoreRankVO.class);
        List<UserScoreRankVO> list = pageVO.getList();
        int startRank = (query.getPageNum() - 1) * query.getPageSize() + 1;
        for (int i = 0; i < list.size(); i++) {
            UserScoreRankVO user = list.get(i);
            user.setRank(startRank + i);
        }

        return pageVO;
    }
}

